import axios from 'axios'
import WConfig from '@/config/index'
import { getToken } from '@/utils/auth'
import { InputChangeEvent } from '@/utils/type/global'
import WpopView from '../utils/popView'

// 创建axios实例
const service = axios.create({
  timeout: 30000, // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (WConfig.store.getters.token) {
      config.headers.Token = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    WConfig.print('================= url ==================')
    WConfig.print(config.url)
    WConfig.print('================= 参数 ==================')
    WConfig.print(config.method === 'get' ? config.params : config.data)
    // 所有请求都带上 authentication
    config.headers.Authentication = WConfig.store.getters.token
    // config.headers['Access-Control-Allow-Headers'] = 'Authentication'
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    WConfig.print('================= response ==================', response.config.url)
    WConfig.print(res)
    if (res.code !== 0) {
      WpopView.msgError(res.msg ? res.msg : '网络错误')
      if (res.code === 13001 || res.code === 13002) {
        WpopView.msgError('请重新登录')
        WConfig.store.dispatch('FED_LOG_OUT')
        WConfig.router.push('/')
      }
      return Promise.reject(res)
    } else {
      return res.data
    }
  },
  (error) => {
    WpopView.msgError(error.message)
    return Promise.reject(error)
  },
)

// 自定义封装git
export function get(url: string, params = {}) {
  return service.get(url, {
    // 请求参数
    params,
  })
}

// 自定义封装POST
export function post(url: string, params = {}) {
  return service.post(url, params)
}

// 图片上传
export function upImage(url: string, name: string, e: InputChangeEvent) {
  const file: File = e.target.files![0];
  // 判断图片大小，超出后直接返回
  const fileSize = file.size
  if (fileSize > (2 * 1024 * 1024)) {
    return Promise.reject({
      code: 1,
      msg: '图片大小不能超所2M',
    })
  }
  // 创建form对象
  const params = new FormData()
  // 通过append向form对象添加数据
  params.append(name, file, file.name)
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

// 上传文件
export function upFile(url: string, params = {}) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}
